package pl.mindstorms.mywords;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper {
	public static final String DB_NAME = "mywords";
	public static final String DB_TABLE_WORDS = "words";
	public static final int DB_VERSION = 1;
	private static final String[] COL = new String[] {
		"_id", "english", "polish", "engspeak"	};
	public static final String CLASSNAME = DBHelper.class.getSimpleName();
	
    private SQLiteDatabase db;
    private final DBOpenHelper dbOpenHelper;
    
    public DBHelper(Context context) {
    	dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, 1);
    	establishDb();
    	
    }
    
    private void establishDb() {
    	if (db == null) {
    		db = dbOpenHelper.getWritableDatabase();
    	}
    }
    
    public void cleanup() {
    	if (db != null) {
    		db.close();
    		db = null;
    	}
    }
    
    public void addWord(String eng, String pol) {
    	ContentValues values = new ContentValues();
    	values.put("english", eng);
    	values.put("polish", pol);
    	db.insert(DBHelper.DB_TABLE_WORDS, null, values);
    }
    
    public int getCount() {
    	Cursor c = null;
    	try {
    		c = db.query(DBHelper.DB_TABLE_WORDS, null, null, null, null, null, null);
    		return c.getCount();
    		
    	} catch (SQLException e) {
    		Log.v("TW", DBHelper.CLASSNAME, e);    		
    	} finally {
    		if (c != null && !c.isClosed())
    			c.close();
    	}
    	
		return 0;
    }
    
    private static class DBOpenHelper extends SQLiteOpenHelper {
		private static final String DB_CREATE = "CREATE TABLE "
    			+ DBHelper.DB_TABLE_WORDS
    			+ " (_id INTEGER PRIMARY KEY, " 
    			+ " english TEXT, "
    			+ " polish TEXT, "
    			+ " engspeak TEXT);";
		
    	public DBOpenHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);			
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			try {
				db.execSQL(DBOpenHelper.DB_CREATE);				
			} catch (SQLException e) {
				Log.e("TW", DBHelper.CLASSNAME, e);
			}			
		}
		
		@Override
		public void onOpen(SQLiteDatabase db) {
			super.onOpen(db);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS "+DBHelper.DB_TABLE_WORDS);
			onCreate(db);			
		}
    	
    } // end class DBOpenHelper
    
	

}
